//
//  MyKeyCaseController.m
//  PropertyMananger
//
//  Created by bh on 17/3/7.
//  Copyright © 2017年 BH. All rights reserved.
//

#import "MyKeyCaseController.h"
#import "MyKeyCaseCell.h"
#import "MDkeyModel.h"

@interface MyKeyCaseController ()
@property (nonatomic,strong) NSMutableArray * keyArray;
@end

@implementation MyKeyCaseController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self initTitleViewName:@"我的钥匙包"];
    
     self.keyArray = [[NSMutableArray alloc]init];
    
    [self initTableViewWithView:self.view frame:CGRectMake(0, 0, BHscreenW, BHscreenH - 64) isGroup:NO];
    
    [self getMDKeyData];
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    
    return self.keyArray.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    MyKeyCaseCell * cell = [MyKeyCaseCell cellWithTableView:tableView];
    
    cell.model = self.keyArray[indexPath.row];
    
    return cell;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    return 90;
    
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{

    MDkeyModel * model = self.keyArray[indexPath.row];
    
        //摇一摇手机震动
        AudioServicesPlaySystemSound(kSystemSoundID_Vibrate);
        //点击摇一摇
        MDManager *manager = [MDManager sharedManager];
        //@[@"00000002&#20650101&#MD_BLZX_C929&#80D5D82970A06D5A36615458CE8133E492D6A9A635D74871F08E3A03DE9A2951&#E60A4FEB3F4B812EAB998627E86EC675&#31851222C929&#BLZXC160600875"] @[@"公司大门"]
        [manager shakeOpenDoorWithUserId:userModel.WorkerID UseKeyIdList:@[model.KeyCode] KeyNameList:@[model.DeviceName] CommunityList:@[model.DeviceName] isSupportShake:YES Success:^(NSDictionary *keyInfo) {
            
            [MBProgressHUD showSuccess:[NSString stringWithFormat:@"%@---开门成功",keyInfo[@"key_name"]] time:2];
            
            
        } Failure:^(ErrorType errorCode) {
            NSString * str = [NSString stringWithFormat:@"%ld",(long)errorCode];
            //开门失败
            [self openDoorFailureWithString:str];
            
        }];
    
}
- (void)getMDKeyData{

    NSDictionary * param = @{
                             @"cid":userModel.CommunityID,
                             @"Phone":userModel.Tel,
                             @"json":@"\{\"jsonEntity\":\{},\"action\":\"getkeylist\",\"version\":\"V1.0\"}",
                             };
    DLog(@"提交的参数 == %@",param);
    [HomeNetWorkRequest postMDKeySuccess:^(id data) {
        NSDictionary * dict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
        
        NSString * str = [NSString stringWithFormat:@"%@",dict[@"Data"]];
        NSData * data2 = [str dataUsingEncoding:NSUTF8StringEncoding];
        NSArray * array = [NSJSONSerialization JSONObjectWithData:data2 options:NSJSONReadingMutableContainers error:nil];
        
        DLog(@"钥匙 === %@",array);
        
        for (NSDictionary * dict in array) {
            
            MDkeyModel * model = [[MDkeyModel alloc]init];
            [model setValuesForKeysWithDictionary:dict];
            
            [self.keyArray addObject:model];
            DLog(@"%@",model.DeviceName);
        }

        [self.tableView reloadData];
        
    } Fail:^(NSString *errorDes) {
        NSLog(@"%@",errorDes);

    } param:param];

}
//开门失败
-(void)openDoorFailureWithString:(NSString *)string{
    
    if([string isEqualToString:@"-2002"]){ //蓝牙未打开
        [self openDoorFailureAlertWithMessage:@"蓝牙未打开，是否打开蓝牙？" Cancel:@"否" Confirm:@"是" Type:string];
        
    }else{
        
        [MBProgressHUD showError:[NSString stringWithFormat:@"开门失败（%@）",string] time:1.5];
    }
}

//开门失败提示信息
-(void)openDoorFailureAlertWithMessage:(NSString *)message Cancel:(NSString *)cancel Confirm:(NSString *)confirm Type:(NSString *)type{
    UIAlertController * alertVC = [UIAlertController alertControllerWithTitle:@"提示" message:message preferredStyle:UIAlertControllerStyleAlert];
    [alertVC addAction:[UIAlertAction actionWithTitle:cancel style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        
    }]];
    [alertVC addAction:[UIAlertAction actionWithTitle:confirm style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        if([type isEqualToString:@"-2002"]){//蓝牙未打开
            NSURL *url = [NSURL URLWithString:@"prefs:root=Bluetooth"];
            
            if ([[UIApplication sharedApplication]canOpenURL:url]) {
                
                [[UIApplication sharedApplication]openURL:url];
            }
        }else if ([type isEqualToString:@"-2013"]||[type isEqualToString:@"-2018"]||[type isEqualToString:@"-2014"]){//钥匙错误 -- 钥匙失效 -- 参数为空
            
            [MBProgressHUD showError:@"钥匙错误或失效了,请联系物业处理" toView:self.view time:1.5];
            
        }
    }]];
    [self presentViewController:alertVC animated:YES completion:nil];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
  
}



@end
